package org.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.annotations.GetForHttp;
import org.example.annotations.PostForHttp;
import org.example.util.HttpUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wxm
 * @date 2025/2/26 8:10
 */
@Aspect
@Component
public class TestInterPostAspect {
    @Pointcut("@annotation(org.example.annotations.PostForHttp)")
    public void testAop(){}

    @After("testAop() && @annotation(postForHttp)")
    public void beforeServiceMethod(JoinPoint joinPoint, PostForHttp postForHttp) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        PostForHttp annotation = method.getAnnotation(PostForHttp.class);
        if (annotation != null) {
            System.out.println("获取到注解的值: " + annotation.url());
            try {
                // 获取 HttpUtils 单例实例
                HttpUtils httpUtils = HttpUtils.getInstance();
                // 定义请求 URL
                StringBuilder urlBuilder = new StringBuilder();
                String[] param = annotation.param();
                String[] body = annotation.body();

                if (param.length > 0 && body.length > 0) {
                    for (int i = 0; i < Math.min(param.length, body.length); i++) {
                        if (i > 0) {
                            urlBuilder.append("&");
                        }
                        // 对参数名和参数值进行 URL 编码
                        String encodedParam = URLEncoder.encode(param[i], StandardCharsets.UTF_8);
                        String encodedValue = URLEncoder.encode(body[i], StandardCharsets.UTF_8);
                        urlBuilder.append(encodedParam).append("=").append(encodedValue);
                    }
                }
                String urlBody = urlBuilder.toString();
                System.out.println("url:" + urlBody);
                // 定义请求头
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", annotation.contentType());

                // 发送 POST 请求
                String postResponse = httpUtils.sendPostRequest(annotation.url(), urlBody, headers);
                System.out.println("POST Response: " + postResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
